﻿Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Imports System.Runtime.Serialization
Imports Newtonsoft.Json

Public Class Script
    Implements iCronTask

    Public Property ScriptId As Integer

    <Index("IX_Name", isunique:=True)>
    <MaxLength(100)>
    <Required>
    Public Property Name As String
    Public Property Description As String

    Public Property CategoryId As Integer?

    <Required>
    Public Property Code As String
    Public Property SingleInstance As Boolean = False

    Public Overridable Property Category As Category
    Public Overridable Property History As ICollection(Of ScriptHistory)
    Public Overridable Property JobSteps As ICollection(Of JobStep)
    Public Overridable Property Tags As ICollection(Of ScriptTag)

    Public Sub New()
        Me.History = New HashSet(Of ScriptHistory)()
        Me.JobSteps = New HashSet(Of JobStep)()
    End Sub
End Class

Public Class ScriptHistory
    Public Property ScriptHistoryId As Int64
    <Required>
    Public Property ScriptId As Integer
    <Required>
    Public Property CronGuid As Guid

    Public Property StartDTO As DateTimeOffset
    Public Property EndDTO As DateTimeOffset?
    <MaxLength(10)>
    Public Property Status As String

    Public Overridable Property Results As ICollection(Of ScriptResult)
    Public Overridable Property Script As Script

    <NotMapped>
    Public Property Parameters As New Hashtable
    Private Property JsonParameters As String
        Get
            If Me.Parameters IsNot Nothing AndAlso Me.Parameters.Count > 0 Then
                Return JsonConvert.SerializeObject(Me.Parameters, Formatting.Indented)
            Else
                Return Nothing
            End If
        End Get
        Set(value As String)
            Me.Parameters = JsonConvert.DeserializeObject(Of Hashtable)(value)
        End Set
    End Property

    Public Sub New()
        Me.Results = New HashSet(Of ScriptResult)()
    End Sub

    Public Class ScriptHistoryConfiguration
        Inherits ModelConfiguration.EntityTypeConfiguration(Of ScriptHistory)
        Public Sub New()
            [Property](Function(x) x.JsonParameters)
        End Sub
    End Class
End Class

Public Class ScriptResult
    Public Property ScriptResultID As Int64
    <Required>
    Public Property ScriptHistoryId As Int64
    <Required>
    Public Property Generated As DateTimeOffset
    <Required> <MaxLength(15)>
    Public Property Type As String
    <Required>
    Public Property Message As String
    Public Overridable Property ScriptHistory As ScriptHistory
End Class
